namespace SimpleWebServices.Web.UI.Html.Elements
{
    using System;
    using System.Xml;
    using System.Xml.Serialization;

    [XmlRoot("textarea")]
    public class TextArea : Control, IAttributeAccesskey, IAttributeReadOnly, IXmlSerializable
    {
        public TextArea()
        {
        }

        public TextArea(Name id)
            : base(id)
        {
        }

        public char? Accesskey
        {
            get;
            set;
        }

        public int? Columns
        {
            get;
            set;
        }

        public bool ReadOnly
        {
            get;
            set;
        }

        public int? Rows
        {
            get;
            set;
        }

        public override string Value
        {
            get;
            set;
        }

        public override IElement Deserialize(string name, string type, string xml)
        {
            IElement result = null;

            if (null == type && "textarea".Equals(name, StringComparison.OrdinalIgnoreCase))
            {
                result = xml.Deserialize<TextArea>();
            }

            return result;
        }

        public override void ReadXml(XmlReader reader)
        {
            base.ReadXml(reader);

            string value = reader.GetAttribute("accesskey");
            if (!string.IsNullOrEmpty(value))
            {
                this.Accesskey = value[0];
            }

            value = reader.GetAttribute("cols");
            if (!string.IsNullOrEmpty(value))
            {
                this.Columns = XmlConvert.ToInt32(value);
            }

            value = reader.GetAttribute("rows");
            if (!string.IsNullOrEmpty(value))
            {
                this.Rows = XmlConvert.ToInt32(value);
            }

            this.ReadOnly = "readonly".Equals(reader.GetAttribute("readonly"), StringComparison.OrdinalIgnoreCase);

            this.Value = reader.ReadString();
        }

        public override void WriteXml(XmlWriter writer)
        {
            base.WriteXml(writer);

            if (this.Accesskey.HasValue)
            {
                writer.WriteAttributeString("accesskey", this.Accesskey.Value.ToString());
            }

            if (this.Columns.HasValue)
            {
                writer.WriteAttributeString("cols", XmlConvert.ToString(this.Columns.Value));
            }

            if (this.Rows.HasValue)
            {
                writer.WriteAttributeString("rows", XmlConvert.ToString(this.Rows.Value));
            }

            if (this.ReadOnly)
            {
                writer.WriteAttributeString("readonly", "readonly");
            }

            writer.WriteRaw(this.Value ?? string.Empty);
        }
    }
}